package com.sdhs.paas.gateway.util;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.reactive.result.view.RequestContext;

import com.sdhs.paas.gateway.model.JwtInfoVO;

public class RequestUtils
{
  private static final String IP_SEPARATOR = ",";

  public static String getAccountName(ServerHttpRequest request)
  {
    if (!request.getHeaders().containsKey("requserid")) {
      return null;
    }
    List<String> headersList = request.getHeaders().get("requserid");
    if(headersList == null || headersList.size() == 0 ){
    	JwtInfoVO account = new JwtInfoVO();
    	return account.getUserId();
    }
    JwtInfoVO account = (JwtInfoVO)JSONUtil.json2obj((String)(headersList.get(0)), JwtInfoVO.class);
    return account.getUserId();
  }

  public static String getIP(HttpServletRequest request)
  {
    String ip = request.getHeader("X-Real-IP");

    if ((StringUtils.isBlank(ip)) || ("unknown".equalsIgnoreCase(ip)))
      ip = request.getHeader("x-forwarded-for");
    else {
      return ip;
    }

    if ((StringUtils.isBlank(ip)) || ("unknown".equalsIgnoreCase(ip))) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    else {
      if (ip.indexOf(",") != -1) {
        ip = ip.substring(0, ip.indexOf(","));
      }
      return ip;
    }

    if ((StringUtils.isBlank(ip)) || ("unknown".equalsIgnoreCase(ip)))
      ip = request.getHeader("WL-Proxy-Client-IP");
    else {
      return ip;
    }

    if ((StringUtils.isBlank(ip)) || ("unknown".equalsIgnoreCase(ip)))
      ip = request.getRemoteAddr();
    else {
      return ip;
    }

    if ((StringUtils.isBlank(ip)) || ("unknown".equalsIgnoreCase(ip))) {
      ip = "";
    }
    return ip;
  }

  public static HttpServletRequest getCurrentRequest()
  {
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    if (requestAttributes == null) {
      throw new IllegalStateException("Current thread does not contain request context.");
    }
    return requestAttributes.getRequest();
  }
}